﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.Entity;
using System.Data;
using System.Reflection.Emit;
using System.Reflection;
using System.Data.Common;
using System.Data.SqlClient;

namespace Empires.Infrastructure.Entities
{
    public static class ContextExtensions
    {
        public static DataTable SqlQueryForDataTatable(this Database db,
               string sql,
               params SqlParameter[] parameters)
        {

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = db.Connection.ConnectionString;
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;

            if (parameters.Length > 0)
            {
                foreach (var item in parameters)
                {
                    cmd.Parameters.Add(item);
                }
            }


            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            return table;
        }

        public static UpdateContext<T> Update<T>(this Context ctx) where T : class
        {
            return new UpdateContext<T>(ctx);
        }

        public static DeleteContext<T> Delete<T>(this Context ctx) where T : class
        {
            return new DeleteContext<T>(ctx);
        }

        public static DataTable ExcuteSQL(this Context ctx, string sqlCommand, params SqlParameter[] parameters)
        {
            return ctx.Database.SqlQueryForDataTatable(sqlCommand, parameters);
        }
    }
}
